package com.yuda.campsite.util;

import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.*;
import java.util.stream.IntStream;


/**
 * 生成邀请码 每月 的 1 日 0 点 可以 在任务列表触发一次
 * 或者自动执行
 */
@EnableScheduling
@Component
public class GeneratorInvitationCode {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    String[] seed = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
            "G", "H", "J", "K", "L", "M", "N", "P", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    /**
     * 每月 的1号 凌晨2点执行 不可轻易更改，否则可能会邀请码重复
     */
//    @Scheduled(cron = "0 0 2 1 * ?")
    public void generatorInvitationCode() throws ExecutionException, InterruptedException {
        HashSet<String> set = Sets.newHashSet();
        stringRedisTemplate.delete("invitationCodeYd");
        int length = seed.length;
        StringBuilder[] stringBuilder = new StringBuilder[1];
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        Future<Object> future = scheduledExecutorService.submit(() -> {
            for (int i = 0; i < 500000; i++) {
                stringBuilder[0] = new StringBuilder();
                for (int i1 = 0; i1 < 8; i1++) {
                    int index = new Random().nextInt(length);
                    if (i1 == 3) {
                        stringBuilder[0].append(seed[index]).append("-");
                    } else {
                        stringBuilder[0].append(seed[index]);
                    }
                }
                set.add(stringBuilder[0].toString());
            }
            return set.size();
        });

        future.get();
        scheduledExecutorService.shutdown();
        System.out.println("生成邀请码的数量：" + set.size());
        stringRedisTemplate.opsForList().leftPushAll("invitationCodeYd", set);
    }

}
